<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="订单编号" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="业务员编号" prop="jobCode">
        <el-input v-model="queryParams.jobCode" placeholder="请输入业务员编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <!-- <el-form-item label="机构名称" prop="organizationId">
        <el-input v-model="queryParams.organizationId" placeholder="请选择机构" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->

      <el-form-item label="机构名称" prop="organizationId">
        <el-tree-select v-model="queryParams.organizationId" :data="organizationOptions" :props="{
          value: 'organizationId',
          label: 'orgName',
          children: 'children',
        }" value-key="organizationId" placeholder="请选择机构" clearable check-strictly @change="handleQuery" />
      </el-form-item>

      <!-- <el-form-item label="交易金额" prop="amount">
        <el-input v-model="queryParams.amount" placeholder="请输入交易金额" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->

      <el-form-item label="业务名称" prop="businessName">
        <el-input v-model="queryParams.businessName" placeholder="请输入业务名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <!-- <el-form-item label="订单提交时间" prop="submitTime">
        <el-date-picker clearable v-model="queryParams.submitTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择订单提交时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="订单提交时间" prop="submitTime">
        <el-date-picker v-model="queryParams.submitTimeRange" type="daterange" value-format="YYYY-MM-DD"
          start-placeholder="开始日期" end-placeholder="结束日期" clearable>
        </el-date-picker>
      </el-form-item>

      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="退款状态" prop="refundStatus">
        <el-select v-model="queryParams.refundStatus" placeholder="请选择退款状态" clearable>
          <el-option v-for="dict in refund_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in wdm_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ruoyi:businessOrder:add']"
          >新增</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['ruoyi:businessOrder:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['ruoyi:businessOrder:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['ruoyi:businessOrder:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 border 添加边框提升可读性 resizable 启用列宽拖拽 -->
    <!-- :header-cell-style="{ background: '#111111' }" -->
    <!-- style="width: 100%" -->
    <el-table v-loading="loading" :data="businessOrderList" border resizable @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- prop="orderId" -->
      <el-table-column label="序号" type="index" width="60" align="center" />
      <!-- <el-table-column label="订单编号" align="center" min-width="240" prop="orderCode" /> -->
      <el-table-column label="姓名" align="center" min-width="150" prop="name" />
      <!-- <el-table-column label="联系电话" align="center" min-width="150" prop="phone" /> -->
      <el-table-column label="所属机构" align="center" min-width="150" prop="orgName" />
      <!-- <el-table-column label="业务员编号" align="center" min-width="150" prop="jobCode" /> -->
      <!-- <el-table-column label="关联员工ID" align="center" prop="employeeId" /> -->
      <!-- <el-table-column label="关联机构ID" align="center" prop="organizationId" /> -->
      <el-table-column label="交易金额" align="center" min-width="150" prop="amount" />
      <el-table-column label="业务名称" align="center" min-width="150" prop="businessName" />

      <el-table-column label="订单状态" min-width="100" align="center" prop="orderStatus">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.orderStatus" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="退款状态" min-width="100" align="center" prop="refundStatus">
        <template #default="scope">
          <el-tag :type="getRefundStatusType(scope.row.refundStatus)">
            <dict-tag :options="refund_status" :value="scope.row.refundStatus" />
          </el-tag>
        </template>
      </el-table-column> -->

      <!-- <el-table-column label="创建人" align="center" min-width="240" prop="createBy" />
      <el-table-column label="订单提交时间" align="center" prop="submitTime" width="180">
        <template #default="scope">
          <span v-if="scope.row.submitTime">{{ parseTime(scope.row.submitTime, "{y}-{m}-{d}") }}</span>
          <span v-else-if="scope.row.startTime && scope.row.endTime">
            {{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }} 至 {{ parseTime(scope.row.endTime, "{y}-{m}-{d}") }}
          </span>
        </template>
      </el-table-column> -->

      <!-- <el-table-column label="修改人" align="center" min-width="240" prop="updateBy" />
      <el-table-column label="更新时间" align="center" min-width="150" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->

      <!-- <el-table-column label="支付类型" align="center" prop="payType">
        <template #default="scope">
          <dict-tag :options="payment_method" :value="scope.row.payType" />
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center" prop="payStatus">
        <template #default="scope">
          <dict-tag :options="payment_status" :value="scope.row.payStatus" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status" />
        </template>
      </el-table-column> -->


      <el-table-column label="操作" min-width="220" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:businessOrder:edit']">审核</el-button> -->

          <!-- 仅当有退款申请且状态为"审核中"时显示审核按钮 -->
          <!-- v-hasPermi="['ruoyi:businessOrder:audit']" -->
          <el-button v-if="scope.row.orderStatus === '3'" link type="warning" icon="Check"
            @click="handleAudit(scope.row)">审核
          </el-button>

          <el-button link type="primary" icon="View" @click="handleView(scope.row)"
            v-hasPermi="['ruoyi:businessOrder:edit']">查看
          </el-button>

          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:businessOrder:remove']">删除
          </el-button>

        </template>
      </el-table-column>

      <el-table-column label="订单提交时间" align="center" prop="submitTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.submitTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注信息" align="center" min-width="150" prop="remark" />
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改业务订单信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="businessOrderRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="订单编号" prop="orderCode">
          <el-input v-model="form.orderCode" placeholder="请输入订单编号" />
        </el-form-item> -->

        <el-form-item label="员工ID" prop="employeeId">
          <el-input v-model="form.employeeId" placeholder="请输入关联员工ID" />
        </el-form-item>
        <el-form-item label="机构ID" prop="organizationId">
          <el-input v-model="form.organizationId" placeholder="请输入关联机构ID" />
        </el-form-item>
        <el-form-item label="交易金额" prop="amount">
          <!-- <el-input v-model="form.amount" placeholder="请输入交易金额" /> -->
          <el-input v-model.number="queryParams.amount" type="number" :precision="2" step="0.01" />
        </el-form-item>
        <el-form-item label="业务名称" prop="businessName">
          <el-input v-model="form.businessName" placeholder="请输入业务名称" />
        </el-form-item>
        <el-form-item label="订单提交时间" prop="submitTime">
          <el-date-picker clearable v-model="form.submitTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择订单提交时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" placeholder="请选择订单状态">
            <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in wdm_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-radio-group v-model="form.delFlag">
            <el-radio v-for="dict in del_flag" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看订单信息对话框 -->
    <el-dialog :title="title" v-model="viewOpen" width="70%" append-to-body custom-class="custom-dialog">
      <div class="dialog-container">
        <!-- 基本信息 -->
        <el-card class="info-card">
          <template #header>
            <div class="clearfix" style="text-align: center">
              <span style="font-size: 20px; color: #1890ff">业务订单基本信息</span>

              <el-descriptions title="基本信息" :model="form" label-width="120px" border>
                <el-descriptions-item label="订单编号">{{
                  form.orderCode
                }}</el-descriptions-item>
                <el-descriptions-item label="员工姓名">{{
                  form.name
                }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{
                  form.phone
                }}</el-descriptions-item>
                <el-descriptions-item label="机构名称">{{
                  form.orgName
                }}</el-descriptions-item>
                <el-descriptions-item label="交易金额">{{
                  form.amount
                }}</el-descriptions-item>
                <el-descriptions-item label="业务名称">{{
                  form.businessName
                }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </template>
        </el-card>

        <!-- 订单状态信息 -->
        <el-card class="status-card">
          <template #header>
            <div class="clearfix" style="text-align: center">
              <span style="font-size: 20px; color: #1890ff">业务订单状态信息</span>

              <el-descriptions title="状态信息" :model="form" label-width="120px" border>
                <el-descriptions-item label="订单状态">{{
                  dictLabel(order_status, form.orderStatus)
                }}</el-descriptions-item>
                <el-descriptions-item label="支付类型">{{
                  dictLabel(payment_method, form.payType)
                }}</el-descriptions-item>
                <el-descriptions-item label="支付状态">{{
                  dictLabel(payment_status, form.payStatus)
                }}</el-descriptions-item>
                <el-descriptions-item label="订单提交时间">{{
                  parseTime(form.submitTime)
                }}</el-descriptions-item>
                <el-descriptions-item label="创建人">{{
                  form.createBy
                }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{
                  parseTime(form.createTime)
                }}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{
                  parseTime(form.updateTime)
                }}</el-descriptions-item>
                <el-descriptions-item label="备注信息" :span="3">{{
                  form.remark
                }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </template>
        </el-card>

        <!-- 在查看订单信息对话框中添加退款信息部分 -->
        <!-- <el-card class="refund-card" v-if="form.refundStatus && form.refundStatus !== '0'">
          <template #header>
            <div class="clearfix" style="text-align: center">
              <span style="font-size: 20px; color: #1890ff">退款信息</span>
            </div>
          </template>

          <el-descriptions :model="form" label-width="120px" border>
            <el-descriptions-item label="退款状态">
              <el-tag :type="getRefundStatusType(form.refundStatus)">
                {{ dictLabel(refund_status, form.refundStatus) }}
              </el-tag>
            </el-descriptions-item>

            <el-descriptions-item label="退款金额">
              {{ formatAmount(form.refundAmt) }}
            </el-descriptions-item>

            <el-descriptions-item label="退款原因">
              {{ dictLabel(refund_reason, form.refundReason) || form.refundReason }}
            </el-descriptions-item>

            <el-descriptions-item label="申请时间">
              {{ parseTime(form.refundApplyTime) }}
            </el-descriptions-item>

            <el-descriptions-item label="审核时间" v-if="form.refundAuditTime">
              {{ parseTime(form.refundAuditTime) }}
            </el-descriptions-item>

            <el-descriptions-item label="审核备注" v-if="form.refundAuditRemark" :span="2">
              {{ form.refundAuditRemark }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card> -->
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 退款审核对话框 -->
    <el-dialog title="退款审核" v-model="auditDialogVisible" width="500px" append-to-body>
      <el-form :model="auditForm" ref="auditFormRef">
        <!-- 订单基本信息 -->
        <el-form-item label="订单编号">
          <span>{{ currentOrder.orderCode }}</span>
        </el-form-item>

        <!-- 退款信息 -->
        <el-form-item label="退款金额">
          <span>¥{{ selectedRefundApplication?.amount || currentOrder.amount }}</span>
        </el-form-item>

        <el-form-item label="退款原因">
          <span>{{ getRefundReasonLabel(selectedRefundApplication?.reason) }}</span>
        </el-form-item>

        <!-- <el-form-item label="退款原因">
          <span>{{ selectedRefundApplication?.reason || '无' }}</span>
        </el-form-item> -->

        <!-- 审核操作 -->
        <el-form-item label="审核结果" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="auditForm.auditStatus === '2'" label="拒绝原因" prop="auditReason"
          :rules="[{ required: true, message: '拒绝原因不能为空' }]">
          <el-input v-model="auditForm.auditReason" type="textarea" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确认</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="BusinessOrder">
import { parseTime } from "@/utils/ruoyi";

import { listOrganization } from "@/api/ruoyi/organization";

import {
  listBusinessOrder,
  listBusinessOrderSummary,
  getBusinessOrder,
  delBusinessOrder,
  addBusinessOrder,
  updateBusinessOrder,

  auditRefundApplication,
} from "@/api/ruoyi/businessOrder";

import {
  listRefundInfo,
  getRefundInfo,
  delRefundInfo,
  addRefundInfo,
  updateRefundInfo,

  getActiveRefundsByOrderId,
  getLatestRefundByOrderId,
} from "@/api/ruoyi/refundInfo";

const { proxy } = getCurrentInstance();
const { wdm_status, order_status, payment_method, payment_status, del_flag, refund_status, refund_reason } =
  proxy.useDict(
    "wdm_status",
    "order_status",
    "payment_method",
    "payment_status",
    "del_flag",
    "refund_status",
    "refund_reason"
  );

const businessOrderList = ref([]);
const refundInfoList = ref([]);


const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  // 新增查看对话框控制变量
  viewOpen: false,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    employeeId: null,
    organizationId: null,
    amount: null,
    businessName: null,
    // 订单提交时间
    submitTime: null,
    // 订单检索时间段
    submitTimeRange: [],

    orderStatus: null,
    status: null,
    orderCode: null,
    name: null,
    phone: null,
    orgName: null,
    jobCode: null,
    payType: null,
    payStatus: null,

    // 退款信息
    paymentId: null,
    orderId: null,
    refundAmt: null,
    refundStatus: null,
    refundReason: null,
    refundTransId: null,
    refundTime: null,
    version: null,
    reason: null,
    refundCode: null,
  },
  rules: {
    employeeId: [
      { required: true, message: "关联员工ID不能为空", trigger: "blur" },
    ],
    organizationId: [
      { required: true, message: "关联机构ID不能为空", trigger: "blur" },
    ],
    delFlag: [
      { required: true, message: "删除标志不能为空", trigger: "change" },
    ],
    // orderCode: [
    //   { required: true, message: "订单编号不能为空", trigger: "blur" }
    // ]
  },
});

const { queryParams, form, rules, viewOpen } = toRefs(data);

// 新增状态变量
const auditDialogVisible = ref(false);
const currentOrder = ref({});
const refundReason = ref('');
const auditForm = reactive({
  auditStatus: '',
  auditReason: ''
});

// 新增状态变量（添加到现有变量声明区域）
const refundApplications = ref([]); // 退款申请列表
const selectedRefundApplication = ref(null); // 当前选中的退款申请

// 审核按钮处理
const handleAudit = async (row) => {
  try {
    // 获取订单详情
    const orderRes = await getBusinessOrder(row.orderId);
    currentOrder.value = orderRes.data;

    // 使用正确的API获取退款信息
    const refundRes = await getActiveRefundsByOrderId(row.orderId);

    // 处理可能的返回结构
    let refundList = [];

    // 处理三种可能的返回结构
    if (Array.isArray(refundRes?.data)) {
      refundList = refundRes.data;
    } else if (refundRes?.data && typeof refundRes.data === 'object' && !Array.isArray(refundRes.data)) {
      refundList = [refundRes.data];
    } else if (Array.isArray(refundRes?.data?.rows)) {
      refundList = refundRes.data.rows;
    }

    refundApplications.value = refundList;

    // 设置默认选中项
    if (refundApplications.value.length > 0) {
      selectedRefundApplication.value = refundApplications.value[0];
      refundReason.value = selectedRefundApplication.value.reason || '用户申请退款';
    } else {
      selectedRefundApplication.value = null;
      refundReason.value = '未找到退款申请';
    }

    // 显示对话框
    auditForm.auditStatus = '';
    auditForm.auditReason = '';
    auditDialogVisible.value = true;
  } catch (error) {
    proxy.$modal.msgError("获取订单信息失败: " + error.message);
  }
};

// const handleAudit = async (row) => {
//   try {
//     // 获取订单详情（包含退款原因）
//     const res = await getBusinessOrder(row.orderId);
//     currentOrder.value = res.data;
//     refundReason.value = res.data.refundReason || '用户申请退款';

//     // 重置表单
//     auditForm.auditStatus = '';
//     auditForm.auditReason = '';
//     auditDialogVisible.value = true;
//   } catch (error) {
//     proxy.$modal.msgError("获取订单信息失败");
//   }
// };




// 提交审核
const submitAudit = () => {
  proxy.$refs.auditFormRef.validate(async (valid) => {
    if (valid) {
      try {
        // 安全检查：确保有退款申请
        if (refundApplications.value.length === 0) {
          throw new Error('该订单没有退款申请');
        }

        // 确保 selectedRefundApplication 有值（关键修复）
        if (!selectedRefundApplication.value && refundApplications.value.length > 0) {
          // 自动设置第一个退款申请
          selectedRefundApplication.value = refundApplications.value[0];
          console.warn('自动选择了第一个退款申请', selectedRefundApplication.value);
        }

        // 确保有选中的退款申请
        if (!selectedRefundApplication.value) {
          throw new Error('未选择退款申请');
        }

        // 获取退款申请ID（确保是数字）
        const refundId = Number(selectedRefundApplication.value.refundId);
        if (isNaN(refundId)) {
          throw new Error('无效的退款申请ID');
        }

        // 调用审核API
        await auditRefundApplication(
          refundId,
          {
            auditStatus: auditForm.auditStatus,
            auditReason: auditForm.auditReason
          }
        );

        proxy.$modal.msgSuccess("审核提交成功");
        auditDialogVisible.value = false;
        getList(); // 刷新订单列表
      } catch (error) {
        proxy.$modal.msgError("审核失败: " + (error.message || error));
      }
    }
  });
};
// const submitAudit = () => {
//   proxy.$refs.auditFormRef.validate(async (valid) => {
//     if (valid) {
//       try {
//         await auditRefundApplication(
//           currentOrder.value.refundId, // 从订单undId, // 从订单数据获取退款ID
//           {
//             auditStatus: auditForm.auditStatus,
//             auditReason: auditForm.auditReason
//           }
//         );

//         proxy.$modal.msgSuccess("审核提交成功");
//         auditDialogVisible.value = false;
//         getList(); // 刷新订单列表
//       } catch (error) {
//         proxy.$modal.msgError("审核失败: " + (error.message || error));
//       }
//     }
//   });
// };


// 退款审核相关变量
const auditOpen = ref(false);
const auditTitle = ref("");


// 获取退款状态类型（用于标签颜色）
function getRefundStatusType(status) {
  switch (status) {
    case '1': return 'warning'; // 申请退款
    case '2': return 'info';    // 审核中
    case '3':
    case '6': return 'success'; // 审核通过、退款成功
    case '4':
    case '7': return 'danger';  // 审核拒绝、退款失败
    default: return 'info';
  }
}

// 退款审核按钮点击
function handleRefundAudit(row, isPass) {
  // 获取退款信息
  getRefundInfoByOrderId(row.orderId).then(response => {
    if (response.data && response.data.length > 0) {
      const refund = response.data[0]; // 假设一个订单只有一个退款申请
      auditForm.value = {
        orderId: row.orderId,
        refundId: refund.refundId,
        refundAmt: refund.refundAmt,
        refundReason: refund.refundReason,
        auditRemark: null,
        auditResult: isPass
      };

      auditTitle.value = `${isPass ? '通过' : '拒绝'}订单【${row.orderCode}】的退款申请`;
      auditOpen.value = true;
    } else {
      proxy.$modal.msgError("未找到退款申请信息");
    }
  }).catch(error => {
    console.error('获取退款信息失败:', error);
    proxy.$modal.msgError("获取退款信息失败");
  });
}

// 获取订单的退款信息
function getRefundInfoByOrderId(orderId) {
  return listRefundInfo({ orderId: orderId });
}

// 提交退款审核
function submitRefundAudit() {
  const params = {
    refundId: auditForm.value.refundId,
    auditResult: auditForm.value.auditResult ? '3' : '4', // 3-通过, 4-拒绝
    auditRemark: auditForm.value.auditRemark
  };

  auditRefund(params).then(response => {
    proxy.$modal.msgSuccess(auditForm.value.auditResult ? "退款审核通过" : "退款审核拒绝");
    auditOpen.value = false;
    handleQuery(); // 刷新列表
  }).catch(error => {
    console.error('退款审核失败:', error);
    proxy.$modal.msgError("退款审核失败");
  });
}

// 退款审核API调用
function auditRefund(params) {
  return new Promise((resolve, reject) => {
    proxy.$axios.post('/api/ruoyi/refundInfo/audit', params)
      .then(response => resolve(response))
      .catch(error => reject(error));
  });
}


/** 查询业务订单信息列表 */
function getList() {
  loading.value = true;
  listBusinessOrderSummary(queryParams.value).then((response) => {
    // businessOrderList.value = response.rows;
    // 过滤已删除数据（假设 delFlag 字段标识删除状态）
    businessOrderList.value = response.rows.filter(
      (item) => item.delFlag !== "2"
    );
    total.value = response.total;
    loading.value = false;
  });
}


/** 查询退款信息日志管理列表 */
function getRefundInfoList() {
  loading.value = true;
  listRefundInfo(queryParams.value).then((response) => {
    // refundInfoList.value = response.rows
    // 过滤已删除数据（假设 delFlag 字段标识删除状态）
    refundInfoList.value = response.rows.filter(
      (item) => item.delFlag !== "2"
    );
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    employeeId: null,
    organizationId: null,
    amount: null,
    businessName: null,
    submitTime: null,
    orderStatus: null,
    status: null,
    delFlag: null,
    version: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
    orderCode: null,
    name: null,
    phone: null,
    orgName: null,
    jobCode: null,
    payType: null,
    payStatus: null,
  };
  proxy.resetForm("businessOrderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;

  // 将时间范围拆分为两个独立参数
  if (
    queryParams.value.submitTimeRange &&
    queryParams.value.submitTimeRange.length === 2
  ) {
    queryParams.value.startTime = queryParams.value.submitTimeRange[0];
    queryParams.value.endTime = queryParams.value.submitTimeRange[1];
  } else {
    queryParams.value.startTime = null;
    queryParams.value.endTime = null;
  }

  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");

  // 重置时间范围选择
  queryParams.value.submitTimeRange = [];

  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加业务订单信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  // const _orderId = row.orderId || ids.value;
  const _orderId = row?.orderId || (ids.value.length > 0 ? ids.value[0] : null);
  getBusinessOrder(_orderId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改业务订单信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["businessOrderRef"].validate((valid) => {
    if (valid) {
      if (form.value.orderId != null) {
        updateBusinessOrder(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBusinessOrder(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value;
  proxy.$modal
    .confirm('是否确认删除业务订单信息编号为"' + _orderIds + '"的数据项？')
    .then(function () {
      return delBusinessOrder(_orderIds);
    })
    .then(() => {
      // getList();
      handleQuery(); // 使用查询方法替代 getList() 保持参数一致性
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/businessOrder/export",
    {
      ...queryParams.value,
    },
    `businessOrder_${new Date().getTime()}.xlsx`
  );
}

/** 查看按钮操作 */
function handleView(row) {
  const _orderId = row?.orderId || (ids.value.length > 0 ? ids.value[0] : null);
  if (!_orderId) {
    proxy.$modal.msgError("请选择要查看的订单");
    return;
  }

  getBusinessOrder(_orderId).then((response) => {
    form.value = response.data;
    title.value = "订单详情查看";
    viewOpen.value = true;
  });
}


// 辅助函数：根据字典值获取标签
function dictLabel(dict, value) {
  const item = dict.find((d) => d.value === value);
  return item ? item.label : value;
}

// 新增：获取退款原因标签
function getRefundReasonLabel(reason) {
  if (!reason) return '无';

  // 安全检查：确保字典已加载
  if (!refund_reason.value || !Array.isArray(refund_reason.value)) {
    return reason; // 如果字典未加载，返回原始值
  }

  // 使用字典数据转换
  const item = refund_reason.value.find(d => d.value === reason);
  return item ? item.label : reason;
}

// 增强时间格式化显示
function formatTime(time) {
  return time ? parseTime(time, "{y}-{m}-{d} {h}:{i}:{s}") : "N/A";
}

// 添加金额格式化
function formatAmount(amount) {
  return amount ? `¥${parseFloat(amount).toFixed(2)}` : "¥0.00";
}
// 新增部分

const organizationOptions = ref([]);
/** 查询机构信息下拉树结构 */
function getTreeselect() {
  listOrganization().then((response) => {
    organizationOptions.value = [];
    const data = { organizationId: 0, orgName: "顶级节点", children: [] };
    data.children = proxy.handleTree(
      response.data,
      "organizationId",
      "parentId"
    );
    organizationOptions.value.push(data);
  });
}

getList();

getRefundInfoList();

// 获取机构信息下拉树结构
getTreeselect();
</script>


<style scoped>
.dialog-container {
  /* display: grid; */
  /* grid-template-columns: 1fr 1fr; */
  gap: 16px;
}

.info-card,
.refund-card {
  grid-column: span 3;
}

.status-card {
  height: 100%;
  width: 100%;
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

/* 在现有样式中添加 */
.refund-info {
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #606266;
}

.no-refund {
  color: #909399;
  font-style: italic;
}
</style>
